package com.jic.purchase.service.impl;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

import cn.hutool.core.collection.CollectionUtil;
import com.alibaba.fastjson.JSONArray;
import com.jic.common.base.vo.PageResult;
import com.jic.purchase.constant.consist.ResponseCode;
import com.jic.purchase.exception.AppRuntimeException;
import com.jic.purchase.model.vo.request.PurchaseContractProductRelRequest;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;

import com.alibaba.fastjson.JSONObject;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;

import javax.annotation.Resource;

import com.jic.purchase.model.vo.response.PurchaseContractProductRelResponse;
import com.jic.purchase.model.entity.PurchaseContractProductRel;
import com.jic.purchase.mapper.PurchaseContractProductRelMapper;
import com.jic.purchase.service.PurchaseContractProductRelService;

import lombok.extern.slf4j.Slf4j;

/**
 * 接口实现类
 *
 * @author : 建投数据科技(山东)有限公司
 * @version : v1.0.0
 * @email :
 * @since : 2020-03-09 10:12:20
 */
@Service
@Slf4j
public class PurchaseContractProductRelServiceImpl implements PurchaseContractProductRelService {

    @Resource
    private PurchaseContractProductRelMapper mapper;


    /**
     * 新增记录
     *
     * @param request 需要保存的入参实体类
     * @return int 是否保存成功
     */
    @Override
    public int save(PurchaseContractProductRel request) {
//        mapper.deleteByContractCode(request.getContractCode());
        int flag = mapper.insert(request);
        if (flag == 1) {
            return 1;
        } else {
            throw new AppRuntimeException(ResponseCode.EXCEPTION, "新增失败");
        }
    }


    /**
     * 保存或修改记录信息
     *
     * @param request 需要保存的入参实体类
     * @return int 是否保存或修改成功
     * author 建投数据科技(山东)有限公司
     * @date 2020-3-11 20:54:09
     */
    @Override
    public int saveOrUpdate(PurchaseContractProductRel request) {
        log.info("保存或修改记录信息，入参 = {}", JSONObject.toJSONString(request));
        try {
            if (request == null) {
                throw new AppRuntimeException(ResponseCode.EXCEPTION, "入参为空");
            }
            if (request.getId() != null) {
                log.info("保存或修改记录信息，修改，入参 = {}", JSONObject.toJSONString(request));
                int flag = mapper.updateByPrimaryKey(request);
                if (flag == 1) {
                    return 1;
                }
            } else {
                log.info("保存或修改记录信息，保存，入参 = {}", JSONObject.toJSONString(request));
                int flag = mapper.insertSelective(request);
                if (flag == 1) {
                    return 1;
                } else {
                    throw new AppRuntimeException(ResponseCode.EXCEPTION, "修改失败");
                }
            }
        } catch (Exception e) {
            log.error("用户保存或修改失败", e);
            throw new AppRuntimeException(ResponseCode.EXCEPTION, "用户保存或修改失败");
        }
        return -1;
    }

    /**
     * 删除记录
     *
     * @param request 需要删除,含有主键的入参实体类
     * @return int 是否删除成功
     */
    @Override
    public int deleteByPrimaryKey(PurchaseContractProductRel request) {
        int flag = mapper.deleteByPrimaryKey(request.getId());
        if (flag == 1) {
            return 1;
        } else {
            throw new AppRuntimeException(ResponseCode.EXCEPTION, "删除失败");
        }
    }


    /**
     * 逻辑删除记录
     *
     * @param request 含有主键的逻辑删除实体类
     * @return int 是否逻辑删除成功
     */
    @Override
    public int deleteByPrimaryKeyLogically(PurchaseContractProductRel request) {
        request.setDeleteFlag(1);
        int flag = mapper.updateByPrimaryKey(request);
        if (flag == 1) {
            return 1;
        } else {
            throw new AppRuntimeException(ResponseCode.EXCEPTION, "逻辑删除记录失败");
        }
    }


    /**
     * 修改
     *
     * @param request
     * @return
     */
    @Override
    public int updateByPrimaryKeySelective(PurchaseContractProductRel request) {
        try {
            log.info("修改记录");
            PurchaseContractProductRel param = new PurchaseContractProductRel();
            BeanUtils.copyProperties(request, param);
            int flag = mapper.updateByPrimaryKeySelective(param);
            if (flag == 1) {
                return 1;
            } else {
                throw new AppRuntimeException(ResponseCode.EXCEPTION, "修改记录失败");
            }
        } catch (Exception e) {
            log.error("修改记录失败", e);
            throw new AppRuntimeException(ResponseCode.EXCEPTION, "修改记录失败");
        }

    }

    /**
     * 记录详情
     *
     * @param request 查询的入参实体类
     * @return 数据库查询到的实体类
     */
    @Override
    public PurchaseContractProductRel getByPrimaryKey(PurchaseContractProductRel request) {
        return mapper.selectByPrimaryKey(request.getId());
    }


    /**
     * 分页查询
     *
     * @param request 分页查询入参实体类
     * @return 含有分页信息的实体类列表
     */
    @Override
    public PageInfo<PurchaseContractProductRel> listPageBySelective(PurchaseContractProductRel request, int pageNum, int pageSize) {
        PageHelper.startPage(pageNum, pageSize);
        PageHelper.orderBy(" create_time desc");
        List<PurchaseContractProductRel> list = mapper.listPageBySelective(request);
        PageInfo pageInfo = new PageInfo(list);
        PageResult<PurchaseContractProductRel> result = new PageResult<>();
        result.setTotal(pageInfo.getTotal());
        result.setRows(list);
        return new PageInfo(list);
    }

    /**
     * 不分页查询
     *
     * @param request 不分页查询入参实体类
     * @return 数据库查到的实体类列表
     */
    @Override
    public List<PurchaseContractProductRel> listAllRecord(PurchaseContractProductRel request) {
        //分页处理
        request.setDeleteFlag(0);
        return mapper.selectBySelective(request);
    }

    /**
     * 退货单操作
     *
     * @param request
     * @return
     */
    @Override
    public Boolean returnOrderOperate(PurchaseContractProductRelRequest request) {
        String products = request.getProducts();
        if (StringUtils.isEmpty(products)) {
            throw new AppRuntimeException(ResponseCode.EXCEPTION, "商品数据不能为空");
        }
        List<PurchaseContractProductRelResponse> list = JSONArray.parseArray(request.getProducts(), PurchaseContractProductRelResponse.class);
        if (CollectionUtil.isEmpty(list)) {
            throw new AppRuntimeException(ResponseCode.EXCEPTION, "商品数据不能为空");
        }
        for (PurchaseContractProductRelResponse product : list) {
            if (product.getReturnNum() > product.getRealRecievedNum()) {
                throw new AppRuntimeException(ResponseCode.EXCEPTION, "退库数量不能大于实收数量");
            }
            //根据退库数量操作对应商品实际入库数量
            PurchaseContractProductRel productRel = new PurchaseContractProductRel();
            productRel.setId(product.getId());
            productRel.setRealRecievedNum(product.getRealRecievedNum() - product.getReturnNum());
            mapper.updateByPrimaryKeySelective(productRel);
            //todo 更新库存
        }

        return true;
    }

    /**
     * 补货单加库存
     *
     * @param request
     * @return
     */
    @Override
    public Boolean addOrderOperate(PurchaseContractProductRelRequest request) {
        String products = request.getProducts();
        if (StringUtils.isEmpty(products)) {
            throw new AppRuntimeException(ResponseCode.EXCEPTION, "商品数据不能为空");
        }
        List<PurchaseContractProductRelResponse> list = JSONArray.parseArray(request.getProducts(), PurchaseContractProductRelResponse.class);
        if (CollectionUtil.isEmpty(list)) {
            throw new AppRuntimeException(ResponseCode.EXCEPTION, "商品数据不能为空");
        }
        for (PurchaseContractProductRelResponse product : list) {
            //根据退库数量操作对应商品实际入库数量
            PurchaseContractProductRel productRel = new PurchaseContractProductRel();
            productRel.setId(product.getId());
            productRel.setRealRecievedNum(product.getRealRecievedNum() + product.getReturnNum());
            mapper.updateByPrimaryKeySelective(productRel);
            //todo 更新库存
        }

        return true;
    }

    @Override
    public void deleteByContractCode(PurchaseContractProductRel purchaseContractProductRel) {
        mapper.deleteByContractCode(purchaseContractProductRel.getContractCode());
    }


}
